package com.gopay.cashier.web.controller.cloud;

import java.text.DecimalFormat;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.gopay.cashier.common.exception.WebException;
import com.gopay.cashier.domain.bean.LoginUser;
import com.gopay.cashier.service.cloud.CloudLoginService;
import com.gopay.cashier.service.impl.AntiPhishServiceImpl;
import com.gopay.cashier.web.command.OrderInfo;
import com.gopay.cashier.web.command.PayInfoCommand;
import com.gopay.cashier.web.controller.BaseController;
import com.gopay.cashier.web.controller.EntryController;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.constants.trans.TxnStaCode;
import com.gopay.common.constants.txncd.IntTxnCd;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.domain.cust.CustCorpInfo;
import com.gopay.common.domain.rcs.RcsAntiPhishViolateLog;

/**
 * 进入收银台前的控制器
 */
@Controller
public class CloudEntryController extends BaseController {
	protected final static Log logger = LogFactory.getLog(EntryController.class);

    @Resource(name = "antiPhishService")
    private AntiPhishServiceImpl antiPhishService;

    @Resource(name="cloudLoginService")
    private CloudLoginService cloudLoginService;
    
    @RequestMapping("/pay/cloud/order.shtml")
    public ModelAndView execute(PayInfoCommand command) throws WebException {
        printRequest();
        
        String orderId = getRequest().getParameter(GOPAY_ORDER_ID);
        //String key = getRequest().getParameter(GOPAY_ORDER_KEY);
        CpsGenMainOrder order = getMainOrder(orderId, true);
        CustCorpInfo cust = custCorpInfoService.get(order.getMerId());
        // 校验
        validate(command, order, cust);
        //关键数据
        initSecData();
        if (!(isInchargeOrder(order) || isP2PInChargeOrder(order))) {
            RcsAntiPhishViolateLog log = rcsAntiPhishingViolateLogManager.getByTransDtlSq(order.getTransDtlSq());
            if (null != log) {// 展示反钓鱼页面
                OrderInfo orderInfo = getOrderInfo(order.getGopayOrderId());
                orderInfo.setOrderAmt(new DecimalFormat("0.00").format(order.getMerTxnAmt()));
                return antiPhishPage(order, cust, log, orderInfo);
            }
        }
        return next(order);
    }


	private ModelAndView antiPhishPage(CpsGenMainOrder order, CustCorpInfo cust, RcsAntiPhishViolateLog log, OrderInfo orderInfo)  throws WebException{
		ModelAndView mav = new ModelAndView("cloud/00100/common/illegalIpCheck");
		mav.addObject("orderId", order.getGopayOrderId());
		mav.addObject("inc", getRequest().getParameter(FIELD_INC));
		mav.addObject("order", orderInfo);
        String[] antiInfo = antiPhishService.getAntiPhishInfo(order);
        mav.addObject("merName",antiInfo[1]);
        mav.addObject("merRefer",antiInfo[3]);
        mav.addObject("goodsInfo",antiInfo[4]);
		return mav;
	}
	
    public  ModelAndView next(CpsGenMainOrder order) throws WebException {
    	ModelAndView mav = new ModelAndView();
    	String newUrl = "/pay/cloud/info.shtml";
    	mav.addObject(GOPAY_ORDER_ID, order.getGopayOrderId());
    	mav.addObject(GOPAY_ORDER_KEY, getOrderKey(order.getGopayOrderId()));
    	
    	//云账户单点登录
    	if(getLoginUser()== null){
    		if(!cloudLoginService.login(this.getRequest(), order, getOrderKey(order.getGopayOrderId()), mav)){
        		return mav;
        	}
    	}
    	/**根据订单号获取当前支付的账户，如果当前支付的用户和登录的用户是同一用户直接认为已经登录，如果当前用户和支付的用户不是同一用户，先将当前用户登出，登录支付用户**/
    	/**云账户优化     zzg 2016-06-21   start**/
    	else{
    		LoginUser lu =getLoginUser();
    		//如果当前用户存在，判断一下当前订单的用户是否和登录的用户一致，如果不一致登出，重新登录当前用户
    		if(!cloudLoginService.checkLogin(lu,order)){
    			this.logger.info("当前支付用户与登录用户非同一用户，登录用户自动退出！登录custId="
    					+lu.getUser().getCustId()+"，支付custId="+order.getPayAcct());
    			//调用Auth登出    如果以后需要加到这里  潜在的风险概率很小
    			SecurityUtils.getSubject().logout();
    	        getRequest().getSession().removeAttribute(CAS_GOPAY_USER);
    			//对新用户做一次登录
    			if(!cloudLoginService.login(this.getRequest(), order, getOrderKey(order.getGopayOrderId()), mav)){
        		return mav;
        	}
    		}
    	}
    	/**云账户优化     zzg 2016-06-21   end**/
		if(isInchargeOrder(order) || getLoginUser()!= null){
			if(isInchargeOrder(order))
                mav.addObject("inc", "y");
			newUrl = "/sec/pay/cloud/info.shtml";
		}
		if(IntTxnCd._00100.value.equals(order.getGopayIntTxnCd())){
			newUrl = "/sec/pay/cloud/info.shtml";
		}
		mav.setViewName("redirect:"+newUrl);
        return mav;
    }

	private void validate(PayInfoCommand command, CpsGenMainOrder order, CustCorpInfo cust) throws WebException {
		if (null == order) {
			logger.error("订单不存在！order not exist!" + command);
			throw new WebException(ProcCodeConstants.PROC_CODE_100E5041);
		}
		if (null == cust) {
			logger.error("商户不存在！cust not exist!" + command);
			throw new WebException(ProcCodeConstants.PROC_CODE_100E5001);
		}
		/*if (!"1".equals(cust.getIsRealNameCertify())) {
			logger.error("商户未通过实名认证！mer IsRealNameCertify != 1!" + order);
			throw new WebException(ProcCodeConstants.PROC_CODE_100E2031);
		}*/
		// 只有挂起状态的订单才能继续支付
		// 如果允许08状态的订单重新发起，由于OUT_STLM_ID有值了，会误判为直连银行
		if (TxnStaCode.TXN_STA_CD_30000.value != (order.getTxnStaCd())) {
			logger.error("订单状态不对！txn_sta_cd wrong!" + order);
			throw new WebException(ProcCodeConstants.PROC_CODE_100E5042);
		}
	}

	private void initSecData(){
		HttpServletRequest request = getRequest();
		
//		String orderId = request.getParameter("orderId");
		
		request.getSession().removeAttribute(CAS_GOPAY_USER);
//        request.getSession().removeAttribute(GOPAY_ORDER_ID);
        
        if(StringUtils.isNotBlank(request.getParameter(FIELD_U))){
        	request.getSession().setAttribute(CAS_GOPAY_USER, request.getParameter(FIELD_U));
        }
//        request.getSession().setAttribute(GOPAY_ORDER_ID, orderId);
	}

}
